<template>
  <div class="wrap wrap_detail" :class="{phone_x: iphonex}">
    <div class="mod_head_pic">
      <img class="head_pic" :src="info.r_thumbnail" alt="" mode="aspectFill" />
    </div>
    <div class="mod_headline">
      <div class="title">{{info.r_title}}</div>
      <div class="desc">
        <div v-html="info.r_assist_info"></div>
      </div>
      <div class="btn_checkin" :class="{none: info.is_sign_in !== 1}" @click="signInRes">
        <i class="iconfont icon-zssignon"></i>
        <template v-if="info.is_have_sign_in === 1">已签到</template>
        <template v-else>签到</template>
      </div>
    </div>

    <div class="mod_box mod_box_goods" :class="{none: goodsTicket.length === 0}">
      <div class="mod_hd">
        <div class="title">门票</div>
      </div>
      <div class="mod_bd">
        <div class="mod_goods">
          <div class="goods_item"
                v-for="item in goodsTicket"
                :key="item.goods_id">
            <div class="title">{{item.goods_title}}</div>
            <div class="desc">{{item.buy_cut_info || '可预定今日'}}</div>
            <div class="item_action">
              <div class="price" v-if="item.is_appointment != 1 ">&yen;{{item.price}}</div>
              <button class="btn_em orange btn_buy_ticket" @click="gotoGoods(item)">{{ item.is_appointment == 1? '预约' : '购买'}}</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="mod_box mod_box_explain" :class="{none: audio.length === 0}">
      <div class="mod_hd">
        <div class="title">讲解</div>
        <div class="subtitle" v-if="audioBuyInfo.show">· 第一条免费试听</div>
        <div class="subtitle" v-if="!audioBuyInfo.show">· 已购可听全部</div>

        <div class="mod_action" :class="{none: !audioBuyInfo.show}">
          <div class="price">&yen;{{audioBuyInfo.price}}</div>
          <button class="btn_em orange btn_buy_audio_1" @click="buyAudio(audioBuyInfo.id)">购买</button>
        </div>
      </div>
      <div class="mod_bd">
        <div class="mod_explain">
          <div v-for="(item, index) in audio"
                :key="item.goods_id"
                class="explain_item"
                :class="{active : item.is_have === 1, 'playing': item.playing, 'none': (index > 4 && hideMoreAudio) }"
                @click="playAudio(item, index)">
            <div class="title">{{item.ssm_title}}</div>
            <div class="voice_block">
              <div class="iconfont" :class="{'icon-zspause': item.playing, 'icon-zsplay ': !item.playing}"></div>
              <div class="voice_progress" :id="'content_' + index">
                <div class="progress_current" :style="{ width: item.progress + '%'}">
                  <div class="progress_btn"
                      :id="'thumb_' + index"
                      @touchstart="start($event, item, index)"
                      @touchmove="move($event, item, index)"
                      @touchend="end($event, item, index)"
                      @touchcancel="end($event, item, index)"></div>
                </div>
              </div>
              <div class="voice_text">{{item.duration}}</div>
              <!-- <img src="/static/img/wave.png" alt="" class="icon_wave icon_wave_png"> -->
              <img src="/static/img/wave2.gif" alt="" class="icon_wave icon_wave_gif">
              <div class="iconfont icon-zssound"></div>
            </div>
          </div>
          <div v-if="audio.length > 5" class="btn_fold" @click="showMoreAudio">
            <span v-if="hideMoreAudio">查看全部<i class="iconfont icon-zsunfold"></i></span>
            <span v-else>收起<i class="iconfont icon-zspickup"></i></span>
          </div>
        </div>
      </div>
    </div>

    <div class="mod_box mod_box_intro" :class="{none: !info.r_info}">
      <div class="mod_hd">
        <div class="title">简介</div>
      </div>
      <div class="mod_bd">
        <div class="mod_intro" :class="{open: !hideMoreDesc, fold: introFold}">
          <div class="intro_content" id="intro_content">
            <div v-html="info.r_info"></div>
            <span class="btm_mask"></span>
          </div>
          <div class="btn_fold"  @click="showMoreDesc">
            <span v-if="hideMoreDesc">展开全部<i class="iconfont icon-zsunfold"></i></span>
            <span v-else>收起<i class="iconfont icon-zspickup"></i></span>
          </div>
        </div>
      </div>
    </div>

    <div class="pop_layer" :class="{none: !showAudioBuyLayer}">
      <div class="pop_buy">
        <div class="pop_title"><img src="/static/img/lingxing.png" alt="" class="dot" />&yen;{{audioBuyInfo.price}}<img src="/static/img/lingxing.png" alt="" class="dot" /></div>
        <div class="pop_desc">
          该条为付费讲解<br/>
          购买即可收听{{info.r_title}}所有讲解
        </div>
        <div class="pop_btns">
          <div class="btn_cancel" @click="closeAudioBuyLayer">取消</div>
          <div class="btn_em btn_buy_audio_2" @click="orderAudioBuy">立即购买</div>
        </div>
      </div>
    </div>

    <div class="mod_box mod_box_goods" :class="{none: relation_series.length === 0}">
      <div class="mod_hd">
        <div class="title">相关商品</div>
      </div>
      <div class="mod_bd">
        <div class="mod_goods">
          <div class="goods_item"
                v-for="item in relation_series"
                :key="item.goods_id">
            <div class="title">{{item.goods_title}}</div>
            <div class="desc">
              {{item.goods_info || '暂无描述'}}
            </div>
            <div class="item_action">
              <!-- <div class="original_price">&yen;120</div> -->
              <div class="price" v-if="item.is_appointment != 1 ">&yen;{{item.price}}</div>
              <button class="btn_em orange btn_related_buy" @click="gotoGoods(item)">{{ item.is_appointment == 1? '预约' : '购买'}}</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="mod_box mod_box_related" :class="{none: infoRelevant.length === 0}">
      <div class="mod_hd">
        <div class="title">附近景点</div>
      </div>
      <div class="mod_bd">
        <div class="mod_grid_pic">
          <div class="grid_item"
                v-for="item in infoRelevant"
                :key="item.r_id"
                @click="gotoRes(item)">
            <div class="figure">
              <img class="pic" :src="item.r_org_image" alt="" />
            </div>
            <div class="title">{{item.r_title}}</div>
            <div class="desc">距离{{item.distance}}m</div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import fly from '@/utils/fly'
import { getOpenid } from '@/utils/login'
import { doPay } from '@/utils/order'
import { reportData } from '@/utils/report'

const backgroundAudioManager = wx.getBackgroundAudioManager()

const dataResArr = []

export default {
  data () {
    return {
      info: {},
      audio: [],
      current: -1,
      hideMoreAudio: true,
      infoRelevant: [],
      goodsTicket: [],
      audioBuyInfo: {
        show: false,
        id: 0,
        price: 0
      },
      showAudioBuyLayer: false,
      hideMoreDesc: true,
      resId: '',
      introFold: false,
      relation_series: []
    }
  },
  computed: {},
  methods: {
    playAudio (item, index) {
      if (item.is_have !== 1) {
        return
      }
      if (this.current !== index || !backgroundAudioManager.src) {
        if (this.current !== -1) {
          let prev = this.audio[this.current]
          prev.playing = false
          prev.disabledDrag = true
          prev.progress = 0
          prev.duration = this.calcTime(prev.duration_s || 0)
        }
        this.current = index
        // let p = item.progress
        backgroundAudioManager.title = item.ssm_title
        backgroundAudioManager.src = item.audio_url
        backgroundAudioManager.epname = this.resId + '-' + this.current
        // if (item.duration_s) {
        //   setTimeout(function () {
        //     backgroundAudioManager.seek(item.duration_s * p / 100)
        //     backgroundAudioManager.play()
        //   }, 300)
        // }
        // 设置个全局变量
        this.$root.$mp.appOptions._audioInfo = {
          title: item.ssm_title,
          resId: this.resId,
          current: this.current
        }
      } else {
        if (item.playing) {
          backgroundAudioManager.pause()
        } else {
          backgroundAudioManager.play()
        }
      }
    },
    calcTime (num) {
      let res = ('0' + Math.floor(num / 60)).slice(-2) + ':' + ('0' + Math.ceil(num % 60)).slice(-2)
      return res
    },
    boundingClientRect (id) {
      return new Promise((resolve, reject) => {
        let query = wx.createSelectorQuery()
        query.select('#' + id).boundingClientRect(rect => {
          resolve(rect)
        }).exec()
      })
    },
    async getThumbPosition (i) {
      const contentBox = await this.boundingClientRect('content_' + i)
      const thumbBox = await this.boundingClientRect('thumb_' + i)
      return {
        left: thumbBox.left - contentBox.left,
        top: thumbBox.top - contentBox.top,
        thumbBoxLeft: thumbBox.left
      }
    },
    async start (event, item, index) {
      if (item.disabledDrag) return
      const position = await this.getThumbPosition(index)
      const thumbClickDetalX = event.clientX - position.thumbBoxLeft
      item.dragState = {
        thumbStartLeft: position.left,
        thumbStartTop: position.top,
        thumbClickDetalX: thumbClickDetalX
      }
    },
    async move (event, item, index) {
      if (item.disabledDrag) return
      const contentBox = await this.boundingClientRect('content_' + index)
      const deltaX = event.pageX - contentBox.left - item.dragState.thumbStartLeft - item.dragState.thumbClickDetalX
      const stepCount = 100
      const newPosition = (item.dragState.thumbStartLeft + deltaX) - (item.dragState.thumbStartLeft + deltaX) % (contentBox.width / stepCount)
      let newProgress = newPosition / contentBox.width
      if (newProgress < 0) {
        newProgress = 0
      } else if (newProgress > 1) {
        newProgress = 1
      }
      let progress = Math.round(newProgress * 100)
      item.progress = progress
    },
    end (event, item, index) {
      if (item.disabledDrag) return
      item.dragState = null
      backgroundAudioManager.seek(item.duration_s * item.progress / 100)
      backgroundAudioManager.play()
    },
    showMoreAudio () {
      if (this.hideMoreAudio) {
        this.hideMoreAudio = false
      } else {
        this.hideMoreAudio = true
      }
    },
    gotoRes (item) {
      wx.navigateTo({
        url: '/pages/detail/main?id=' + item.r_id
      })
    },
    gotoGoods (item) {
      if (item.gt_id === 3) {
        wx.navigateTo({
          url: '/pages/detail/main?id=' + item.r_id
        })
      } else {
        wx.navigateTo({
          url: '/pages/goods-detail/main?id=' + item.goods_id
        })
      }
    },
    buyAudio (id) {
      this.showAudioBuyLayer = true
      reportData({
        funcx: '景点-语音付费弹窗',
        keyx: id
      })
    },
    closeAudioBuyLayer () {
      this.showAudioBuyLayer = false
    },
    async orderAudioBuy () {
      let openid = await getOpenid()
      let res = await fly.post(`Order/post?wx_openid=${openid}&goods_id=${this.audioBuyInfo.id}&quantity=1`)
      if (res && res.code === 200 && res.data && res.data.order_sn) {
        let wxPayRes = await doPay(res.data.order_sn)
        if (wxPayRes && wxPayRes.code === 200) {
          this.showAudioBuyLayer = false
          await this.loadData()
        }
      } else {
        wx.showToast({
          title: `下单失败${res ? ('(' + res.code + ')') : ''}`,
          icon: 'none'
        })
      }
    },
    showMoreDesc () {
      if (this.hideMoreDesc) {
        this.hideMoreDesc = false
      } else {
        this.hideMoreDesc = true
      }
    },
    async loadData () {
      var that = this
      wx.showLoading({
        title: '加载中'
      })
      let openid = await getOpenid()
      let res = await fly.post(`Resource/get?r_id=${this.resId}&wx_openid=${openid}`)
      wx.hideLoading()
      if (res && res.code === 200 && res.data) {
        this.info = res.data.info

        this.info.r_info = this.info.r_info.replace(/<img/gi, '<img style="max-width:100%;height:auto;margin: 15px auto;" ')

        let audioBuyInfo

        // 渲染音频
        res.data.goods_audio.forEach((item, j) => {
          item.duration = this.calcTime(item.playtime || 0)
          item.progress = 0
          item.playing = false
          item.disabledDrag = true

          // 第一条音频设置为可听
          if (j === 0) {
            item.is_have = 1
          }
          // 取第一条用户未购买的音频作为商品走商品购买流程
          if (!audioBuyInfo && item.is_have === 0) {
            audioBuyInfo = {
              goods_id: item.goods_id,
              price: item.price
            }
          }
        })
        this.audio = res.data.goods_audio
        if (audioBuyInfo) {
          this.audioBuyInfo.show = true
          this.audioBuyInfo.id = audioBuyInfo.goods_id
          this.audioBuyInfo.price = audioBuyInfo.price
        } else {
          this.audioBuyInfo.show = false
        }

        // 附近景点
        this.infoRelevant = res.data.info_relevant
        this.relation_series = res.data.relation_series || []
        // 商品
        this.goodsTicket = res.data.goods_ticket

        // 简介高度计算
        setTimeout(function () {
          wx.createSelectorQuery().select('#intro_content').boundingClientRect(
            function (rect) {
              if (rect.height >= 96) {
                that.introFold = true
              } else {
                that.introFold = false
              }
            }
          ).exec()
        }, 100)
      } else {

      }
    },
    async signInRes () {
      if (this.info.is_have_sign_in === 1) {
        return
      }
      let openid = await getOpenid()
      let rid = this.resId
      let res = await fly.post(`User/signIn?r_id=${rid}&wx_openid=${openid}`)
      if (res && res.code === 200 && res.data) {
        this.info.is_have_sign_in = 1
        wx.showToast({
          title: '签到成功'
        })
        // 设置个全局变量，里面签到影响外面
        this.$root.$mp.appOptions['_resSign_' + rid] = true
      } else {

      }
    },
    initBackAudio () {
      let audioInfo = this.$root.$mp.appOptions._audioInfo

      if (audioInfo === undefined && backgroundAudioManager && backgroundAudioManager.epname) {
        let epname = backgroundAudioManager.epname.split('-')
        audioInfo = {
          resId: epname[0],
          current: epname[1]
        }
      }

      if (audioInfo && !backgroundAudioManager.paused && audioInfo.resId === this.resId) {
        this.current = audioInfo.current
        if (this.audio[this.current]) {
          this.audio[this.current].playing = true
        }
      }
      backgroundAudioManager.onPlay(res => {
        let item = this.audio[this.current]
        if (!item) {
          return
        }
        item.playing = true
        item.disabledDrag = false
      })
      backgroundAudioManager.onTimeUpdate(res => {
        let item = this.audio[this.current]
        if (!item) {
          return
        }
        if (!item.duration_s) {
          item.duration_s = backgroundAudioManager.duration
          // item.duration = this.calcTime(backgroundAudioManager.duration)
        } else {
          item.duration = this.calcTime(backgroundAudioManager.duration - backgroundAudioManager.currentTime)
        }
        if (!item.dragState) {
          item.progress = Math.ceil(backgroundAudioManager.currentTime * 100 / backgroundAudioManager.duration)
        }
      })
      backgroundAudioManager.onPause(res => {
        let item = this.audio[this.current]
        if (!item) {
          return
        }
        item.playing = false
      })
      backgroundAudioManager.onStop(res => {
        let item = this.audio[this.current]
        if (!item) {
          return
        }
        item.playing = false
        item.disabledDrag = true
      })
      backgroundAudioManager.onEnded(res => {
        let item = this.audio[this.current]
        let that = this
        if (!item) {
          return
        }
        item.progress = 0
        item.playing = false
        item.duration = this.calcTime(item.playtime || 0)
        setTimeout(function () {
          item.duration = that.calcTime(item.playtime || 0)
        }, 200)
      })
    }
  },
  async onLoad (options) {
    Object.assign(this.$data, this.$options.data())

    // 重置参数
    this.current = -1
    this.hideMoreAudio = true
    this.showAudioBuyLayer = false
    this.hideMoreDesc = true

    let {
      id
    } = this.$root.$mp.query

    let scene = decodeURIComponent(options.scene || '')
    let _sence = scene.match(/id=(\d+)/)
    if (_sence && _sence.length > 1) {
      id = _sence[1]
    }

    let _from = scene.replace('?', '').replace(/&id=\d+/, '').replace(/^id=\d+/, '')

    this.from = _from

    reportData({
      funcx: '商品详情-景点',
      keyx: id,
      from: this.from
    })
    this.from = ''
    this.resId = id

    await this.loadData()

    this.initBackAudio()

    dataResArr.push({ ...this.$data })
  },
  onUnload () {
    dataResArr.pop()
    const dataNum = dataResArr.length
    if (!dataNum) return
    Object.assign(this.$data, dataResArr[dataNum - 1])
  },
  onShow () {
    var that = this
    that.initBackAudio()

    // 简介高度计算
    setTimeout(function () {
      wx.createSelectorQuery().select('#intro_content').boundingClientRect(
        function (rect) {
          if (rect.height >= 96) {
            that.introFold = true
          } else {
            that.introFold = false
          }
        }
      ).exec()
    }, 100)
  }
}
</script>

<style lang="scss">
  @import './detail.scss';
</style>
